package com.z.springkotlinz.service

import com.z.springkotlinz.domain.User
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.Update
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service

@Service
class UserServiceImpl(
        val mongoTemplate: MongoTemplate
) : IUserService {
    override fun save(user: User): ResponseEntity<Unit> {
       mongoTemplate.save(user)
       return ResponseEntity.noContent().build()
    }

    override fun update(user: User): ResponseEntity<Unit> {
        val query = Query(Criteria.where("id").`is`(user.id))
        val update = Update().set("userName", user.userName).set("passWord", user.password)
        mongoTemplate.updateFirst(query,update,User::class.java)

        return ResponseEntity.noContent().build()

    }

    override fun list(id: Long): ResponseEntity<User> {
        val query = Query(Criteria.where("id").`is`(id))
        val user = mongoTemplate.findOne(query, User::class.java)
        return ResponseEntity.ok(user!!)
    }

    override fun delete(id: Long): ResponseEntity<Unit> {
        val query = Query(Criteria.where("id").`is`(id))
        val user = mongoTemplate.remove(query, User::class.java)
        return ResponseEntity.noContent().build()
    }


}